/**
 * @file gitee.js
 * @description Gitee API服务
 */

class GiteeService {
    constructor() {
        this.baseUrl = 'https://gitee.com/api/v5';
        this.config = null;
    }

    /**
     * 初始化配置
     * @param {Object} config 配置信息
     * @param {string} config.token Gitee访问令牌
     * @param {string} config.owner 仓库所有者
     * @param {string} config.repo 仓库名称
     */
    init(config) {
        this.config = config;
        console.log('Gitee配置已初始化:', {
            owner: config.owner,
            repo: config.repo,
            tokenLength: config.token ? config.token.length : 0
        });
    }

    /**
     * 获取配置
     * @returns {Promise<Object>} 配置信息
     */
    async getConfig() {
        try {
            const result = await chrome.storage.sync.get('giteeConfig');
            console.log('获取到的Gitee配置:', {
                hasConfig: !!result.giteeConfig,
                owner: result.giteeConfig?.owner,
                repo: result.giteeConfig?.repo,
                hasToken: !!result.giteeConfig?.token
            });
            return result.giteeConfig;
        } catch (error) {
            console.error('获取Gitee配置失败:', error);
            throw error;
        }
    }

    /**
     * 保存配置
     * @param {Object} config 配置信息
     */
    async saveConfig(config) {
        try {
            await chrome.storage.sync.set({ giteeConfig: config });
            this.config = config;
            console.log('Gitee配置保存成功');
        } catch (error) {
            console.error('保存Gitee配置失败:', error);
            throw error;
        }
    }

    /**
     * 获取请求头
     * @private
     * @returns {Object} 请求头对象
     */
    _getHeaders() {
        if (!this.config?.token) {
            throw new Error('未配置访问令牌');
        }
        return {
            'Authorization': `token ${this.config.token}`,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        };
    }

    /**
     * 获取目录内容
     * @param {string} path 目录路径
     * @returns {Promise<Array>} 目录内容列表
     */
    async getDirectories(path = '') {
        if (!this.config) {
            throw new Error('请先配置Gitee信息');
        }

        const { owner, repo } = this.config;
        const apiUrl = `${this.baseUrl}/repos/${owner}/${repo}/contents/${path}`;
        
        console.log('请求Gitee API:', {
            url: apiUrl,
            method: 'GET',
            hasToken: !!this.config.token
        });

        try {
            const response = await fetch(apiUrl, {
                headers: this._getHeaders()
            });
            
            if (!response.ok) {
                const errorText = await response.text();
                console.error('Gitee API响应错误:', {
                    status: response.status,
                    statusText: response.statusText,
                    errorText,
                    requestUrl: apiUrl
                });
                throw new Error(`获取目录失败: ${response.status} - ${errorText}`);
            }
            
            const data = await response.json();
            console.log('获取到的目录数据:', {
                totalItems: data.length,
                directories: data.filter(item => item.type === 'dir').length
            });
            
            return data.filter(item => item.type === 'dir');
        } catch (error) {
            console.error('获取目录失败:', {
                error: error.message,
                config: {
                    owner,
                    repo,
                    hasToken: !!this.config.token
                }
            });
            throw error;
        }
    }

    /**
     * 创建目录
     * @param {string} path 目录路径
     * @returns {Promise<Object>} 创建结果
     */
    async createDirectory(path) {
        if (!this.config) {
            throw new Error('请先配置Gitee信息');
        }

        const { owner, repo } = this.config;
        const apiUrl = `${this.baseUrl}/repos/${owner}/${repo}/contents/${path}/.gitkeep`;

        console.log('创建目录:', {
            url: apiUrl,
            path
        });

        try {
            // 创建一个包含注释的.gitkeep文件
            const content = '# This is a placeholder file to create directory';
            const base64Content = btoa(unescape(encodeURIComponent(content)));
            
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: this._getHeaders(),
                body: JSON.stringify({
                    content: base64Content,
                    message: `feat: create directory ${path}`,
                    branch: 'master'
                })
            });

            if (!response.ok) {
                const errorText = await response.text();
                console.error('创建目录失败:', {
                    status: response.status,
                    statusText: response.statusText,
                    errorText
                });
                throw new Error(`创建目录失败: ${response.status} - ${errorText}`);
            }

            const result = await response.json();
            console.log('目录创建成功:', {
                path,
                commitSha: result.commit?.sha
            });
            return result;
        } catch (error) {
            console.error('创建目录请求失败:', error);
            throw error;
        }
    }

    /**
     * 上传文件
     * @param {Object} params 上传参数
     * @param {string} params.path 文件路径
     * @param {string} params.content 文件内容
     * @param {string} [params.message] 提交信息
     * @returns {Promise<Object>} 上传结果
     */
    async uploadFile(params) {
        if (!this.config) {
            throw new Error('请先配置Gitee信息');
        }

        const { owner, repo } = this.config;
        const { path, content, message = `feat: upload ${path}` } = params;
        const apiUrl = `${this.baseUrl}/repos/${owner}/${repo}/contents/${path}`;

        console.log('上传文件:', {
            url: apiUrl,
            path,
            contentLength: content.length
        });

        try {
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: this._getHeaders(),
                body: JSON.stringify({
                    content: btoa(unescape(encodeURIComponent(content))),
                    message,
                    branch: 'master'
                })
            });

            if (!response.ok) {
                const errorText = await response.text();
                console.error('上传文件失败:', {
                    status: response.status,
                    statusText: response.statusText,
                    errorText
                });
                throw new Error(`上传文件失败: ${response.status} - ${errorText}`);
            }

            const result = await response.json();
            console.log('文件上传成功:', {
                path,
                commitSha: result.commit?.sha
            });
            return result;
        } catch (error) {
            console.error('上传文件请求失败:', error);
            throw error;
        }
    }
}

export const giteeService = new GiteeService(); 